﻿using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Core.DynamicForm.PlugIn.ControlModel;
using Kingdee.BOS.Core.List;
using Kingdee.BOS.Core.Metadata.EntityElement;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.Util;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RK.FormPlugin.GFT
{
    [Description("GFT:申购物料差异查询插件"), HotUpdate]
    public class Pae_xgwlcycx : AbstractDynamicFormPlugIn
    {
        public override void BeforeDoOperation(BeforeDoOperationEventArgs e)
        {
            base.BeforeDoOperation(e);
            string key;
            switch (key = e.Operation.FormOperation.Operation.ToUpperInvariant())
            {
                case "SELECTDATA":
                    {
                        this.GetSalOrderInfo();
                        return;
                    }
            }
        }
        public override void AfterBarItemClick(AfterBarItemClickEventArgs e)
        {
            base.AfterBarItemClick(e);
            switch (e.BarItemKey)
            {
                case "tbFresh":  //刷新
                    {
                        List<string> fidlist = new List<string>();
                        for (int i = 0; i < this.Model.GetEntryRowCount("FEntity2"); i++)
                        {
                            if (this.Model.GetValue("FCheckEd", i).ToString() == "True")
                            { fidlist.Add(this.Model.GetValue("FDetailsId", i).ToString()); }
                        }
                        if (fidlist.Count == 0)
                        { this.Model.DeleteEntryData("FEntity"); }
                        else
                        {
                            this.Model.BeginIniti();
                            this.fillgrid(fidlist);
                            this.Model.EndIniti();
                        }
                        this.View.UpdateView("FEntity");
                        break;
                    }
                case "tbSelect":   //反选
                    {
                        this.Model.BeginIniti();
                        for (int i = 0; i < this.Model.GetEntryRowCount("FEntity2"); i++)
                        { this.Model.SetValue("FCheckEd", this.Model.GetValue("FCheckEd", i).ToString() == "True" ? 0 : 1, i); }
                        this.Model.EndIniti();
                        this.View.UpdateView("FEntity2");
                        break;
                    }
                case "tb_BtmSave"://保存损耗率
                    {
                        StringBuilder sb = new StringBuilder();
                        sb.AppendLine("/*dialect*/ ");
                        string partno = "", rate = "0";
                        for (int i = 0; i < this.Model.GetEntryRowCount("FEntity"); i++)
                        {
                            partno = ((DynamicObject)this.Model.GetValue("FMaterialId", i))[1].ToString();
                            rate = this.Model.GetValue("FRate", i).ToString();
                            sb.AppendLine(string.Format("if  (select count(1)  from T_PUR_MaterialRate where FMaterialId={0})=0", partno));
                            sb.AppendLine(string.Format("insert into T_PUR_MaterialRate(FMaterialId,frate,FUserId,ModifyDate) select {0},{1},{2},getdate()", partno, rate, this.Context.UserId.ToString()));
                            sb.AppendLine("else");
                            sb.AppendLine(string.Format("update T_PUR_MaterialRate set FRate={0},ModifyDate=getdate() where FMaterialId={1}", rate, partno));
                        }
                        if (sb.ToString().Length > 10)
                        {
                            try
                            { DBServiceHelper.Execute(this.Context, sb.ToString()); this.View.ShowMessage("保存损耗率成功！"); }
                            catch { this.View.ShowErrMessage("保存损耗率失败！"); }
                        }
                        break;
                    }
                //清除无用记录
                case "tbDelete":
                    {
                        this.Model.BeginIniti();
                        for (int i = 0; i < this.Model.GetEntryRowCount("FEntity2"); i++)
                        {
                            if (this.Model.GetValue("FCheckEd", i).ToString() == "False")
                            {
                                this.Model.DeleteEntryRow("FEntity2", i);
                                i -= 1;
                            }
                        }
                        this.Model.EndIniti();
                        this.View.UpdateView("FEntity2");
                        break;
                    }
            }
        }

        private void GetSalOrderInfo()
        {
            ListSelBillShowParameter para = new ListSelBillShowParameter();
            para.FormId = "SAL_SaleOrder";
            para.ParentPageId = this.View.PageId;
            para.MultiSelect = true;
            para.ListFilterParameter.Filter = "  FDOCUMENTSTATUS = 'C' AND FCANCELSTATUS = 'A'";// AND FCLOSESTATUS = 'A'"; 
            this.View.ShowForm(para, new Action<FormResult>(result =>
            {
                ListSelectedRowCollection selected = result.ReturnData as ListSelectedRowCollection;
                if (result != null && result.ReturnData != null && (result.ReturnData as ListSelectedRowCollection).Count > 0)
                {
                    List<string> fidlist = new List<string>();
                    for (int i = 0; i < selected.Count; i++)
                    { fidlist.Add(selected[i].EntryPrimaryKeyValue.ToString()); }
                    this.ShowSummaryData(fidlist);
                }
            }));
        }

        [Obsolete]
        private void ShowSummaryData(List<string> fidlist)
        {
            if (fidlist.Count > 0)
            {
                List<Task> tasklist = new List<Task>();
                TaskFactory taskfactory = new TaskFactory();
                List<int> listrow = new List<int>();
                //刷已选中销售订单
                this.Model.BeginIniti();
                tasklist.Add(taskfactory.StartNew(() =>
                {
                    this.Model.DeleteEntryData("FEntity2");
                    Entity entity2 = (Entity)this.View.Model.BusinessInfo.GetEntryEntity("FEntity2");
                    DynamicObjectCollection dyEntity2 = this.View.Model.GetEntityDataObject(entity2);
                    string sql = string.Format("/*dialect*/ select  b.FENTRYID,a.FBILLNO,a.fdate,a.FCUSTID,b.FMATERIALID,b.fqty,b.FMTONO,b.FBOMID,b.F_MAT_GROUP from T_SAL_ORDER a inner join T_SAL_ORDERENTRY b on a.fid=b.FID where b.FENTRYID in ({0})", string.Join(",", fidlist));
                    using (IDataReader rd = DBServiceHelper.ExecuteReader(this.Context, sql))
                    {
                        int i = 1;
                        while (rd.Read())
                        {
                            DynamicObject newRow = new DynamicObject(dyEntity2.DynamicCollectionItemPropertyType);
                            newRow = new DynamicObject(dyEntity2.DynamicCollectionItemPropertyType);
                            newRow["Seq"] = i;
                            newRow["FDetailsId"] = rd["FENTRYID"];
                            newRow["FCheckEd"] = true;
                            newRow["FSoNo"] = rd["FBILLNO"];
                            newRow["FSoDate"] = rd["fdate"];
                            newRow["FCustId_Id"] = rd["FCUSTID"];
                            newRow["FMaterial_Id"] = rd["FMATERIALID"];
                            newRow["FSoQty"] = rd["fqty"];
                            newRow["FOc"] = rd["FMTONO"];
                            newRow["FMaterialGroup"] = rd["F_MAT_GROUP"];
                            if (rd["FBOMID"].ToString() == "0")
                            { listrow.Add(i - 1); }
                            i += 1;
                            dyEntity2.Add(newRow);
                        }
                    }
                    DBServiceHelper.LoadReferenceObject(this.Context, dyEntity2.ToArray(), dyEntity2.DynamicCollectionItemPropertyType, false);
                    EntryGrid grid = this.View.GetControl<EntryGrid>("FEntity2");

                    for (int i = 0; i < listrow.Count; i++)
                    {
                        grid.SetRowBackcolor("#FFFF00", listrow[i]);
                        //grid.SetBackcolor("FSoNo","#FFFF00", i); 
                    }
                }));
                //刷用料差异
                tasklist.Add(taskfactory.StartNew(() =>
                {
                    this.fillgrid(fidlist);
                }));
                Task.WaitAll(tasklist.ToArray());
                this.Model.EndIniti();
                this.View.UpdateView();
            }
        }

        private void fillgrid(List<string> fidlist)
        {
            this.Model.DeleteEntryData("FEntity");
            Entity entity = (Entity)this.View.Model.BusinessInfo.GetEntryEntity("FEntity");
            DynamicObjectCollection dyEntity = this.View.Model.GetEntityDataObject(entity);
            string sql = string.Format("/*dialect*/ execute yls_partlistByBomid '{0}'", string.Join(",", fidlist));
            using (IDataReader rd = DBServiceHelper.ExecuteReader(this.Context, sql))
            {
                int i = 1;
                while (rd.Read())
                {
                    DynamicObject newRow = new DynamicObject(dyEntity.DynamicCollectionItemPropertyType);
                    newRow = new DynamicObject(dyEntity.DynamicCollectionItemPropertyType);
                    newRow["Seq"] = i;
                    newRow["FMaterialId_Id"] = rd["fmaterialid"];
                    newRow["FPublic"] = rd["fispublic"];
                    newRow["FCoQty"] = rd["fcoqty"];
                    newRow["FMustQty"] = rd["fmustqty"];
                    newRow["FPoQty"] = rd["fpoqty"];
                    newRow["FRate"] = rd["frate"];
                    newRow["FFollowQty"] = rd["fdiffqty"];
                    newRow["FStoreQty"] = rd["fstoreqty"];
                    newRow["FPrice"] = rd["fprice"];
                    newRow["FBb_Id"] = rd["fbb"];
                    i += 1;
                    dyEntity.Add(newRow);
                }
            }
            DBServiceHelper.LoadReferenceObject(this.Context, dyEntity.ToArray(), dyEntity.DynamicCollectionItemPropertyType, false);
        }
    }
}
